import Taro, { useDidShow } from '@tarojs/taro'
import React, { useState, useCallback, useLayoutEffect, useRef } from 'react'
import { getPlatform, isWxBrowser, isMiniprogramBrowser } from '@UTILS/common'
import { View, Text, Image } from '@tarojs/components'
import i18n from '@I18N'
import Images from '@ASSET/Images'
import style from './index.module.scss'
const { isRN } = getPlatform()

interface Props {
  text: string
  textClass: string
  numberOfLines: number
  lineHeight: number
  collapseText?: string; // 收起文字
  expandText?: string; // 展开文字
  onlyShowExpand?: boolean
  onClick?: (e?: unknown) => void
  showPrefix?: boolean
  containerClass?: string
  expandTextClass?: string
  expandTextBgClass?: string
  hiddenBtnIcon?: boolean
  onClickExpand?: (expand: boolean)=> void
}

const ExpandText: React.FC<Props> = ({
  text = '', numberOfLines = 2, collapseText = i18n.common.collapse(), expandText = i18n.common.expand(), onlyShowExpand = false,
  onClick, showPrefix, textClass, containerClass, lineHeight = 24,
  expandTextClass, hiddenBtnIcon = false, expandTextBgClass, onClickExpand
}) => {
  const ref = useRef()
  const shouldRef = useRef(false)
  const [tempNumberOfLines, setTempNumberOfLines] = useState(numberOfLines + 1)
  const [expand, setExpand] = useState(false)
  const [showExpand, setShowExpand] = useState(false)
  const normalTextStyle = isRN ? {} : { '-webkit-line-clamp': 'unset', maxHeight: 'unset' }
  const moreLineTextStyle = isRN ? {} : { '-webkit-line-clamp': tempNumberOfLines.toString(), maxHeight: `${tempNumberOfLines * (lineHeight)}PX` }
  const dynamicTextStyle = expand ? normalTextStyle : moreLineTextStyle
  const lineHeightStyle = { lineHeight: `${lineHeight}PX` }
  const onClickText = useCallback(
    () => {
      setExpand(!expand)
      onClickExpand?.(!expand)
    },
    [expand, onClickExpand],
  )

  const onClickOnlyShowText = useCallback(
    () => {
      onClick?.()
    },
    [onClick],
  )
  const setHeightExpand = useCallback((isInit: boolean) => {
    const query = Taro.createSelectorQuery()
    query.select('#expandText').boundingClientRect(res => {
      let height = res?.height
      if (getPlatform().isWeb && !height) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        height = ref.current?.offsetHeight
      }
      if (height === undefined) {
        isInit && setTimeout(() => setHeightExpand(false), 100)
        !isInit && (shouldRef.current = true)
        return
      }
      shouldRef.current = false

      // h5 端切换路由时取到的 height 值会有几像素的差距，多加 0.5 的行高避免误渲染
      const realMaxHeight = (numberOfLines + 0.5) * lineHeight
      if (height > realMaxHeight) {
        setShowExpand(true)
      }
      setTempNumberOfLines(numberOfLines)
    }).exec()
  }, [lineHeight, numberOfLines])
  useDidShow(() => {
    if (!shouldRef.current) return
    setHeightExpand(false)
  })
  useLayoutEffect(
    () => {
      Taro.nextTick(() => {
        if (isWxBrowser() && !isMiniprogramBrowser()) {
          setTimeout(() => {
            setHeightExpand(true)
          }, 1000)
          return
        }

        setHeightExpand(true)
      })
    },
    [numberOfLines, showPrefix, text, lineHeight, setHeightExpand]
  )

  if (!text) return null

  return (
    <View className={`${style.expandContainer} ${containerClass}`}>
      {showPrefix && <Image src={Images.doctor.good_at} className={style.prefixImage} />}
      <Text
        ref={ref}
        id="expandText"
        className={`${style.expandText} ${showPrefix ? style.indent : ''} ${textClass}`}
        style={({ ...(onlyShowExpand ? moreLineTextStyle : dynamicTextStyle), ...lineHeightStyle })}
      >
        {text}
      </Text>

      {onlyShowExpand && showExpand ? (
        <Text className={`${style.handleText} ${style.handleTextLineEnd} ${expandTextClass}`} onClick={onClickOnlyShowText}>
          {expandText}
          {!hiddenBtnIcon && <Text className={style.moreIcon} /> }
        </Text>
      ) : (
        showExpand && (
          <Text
            style={lineHeightStyle}
            onClick={onClickText}
            className={`${style.handleText} ${expand ? '' : `${style.handleTextLineEnd} ${expandTextBgClass}`} ${expandTextClass}`}
          >
            <Text>{expand ? collapseText : expandText}</Text>
            {!hiddenBtnIcon && <Text className={`${expand ? style.collapseIcon : style.expandIcon}`} />}
          </Text>
        )
      )}
    </View>
  )
}

export default ExpandText
